use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppConfig {
    pub install_path: String,
    pub steamcmd_path: String,
    pub scum_server_exe_path: String,
    pub scum_server_installed: bool,
    pub frp_dir: String,
    pub frp_installed: bool,
    pub frp_running: bool,
    pub frp_config: HashMap<String, String>,
    pub scum_server_running: bool,
    pub auto_restart_tasks: Vec<AutoRestartTask>,
    pub settings: HashMap<String, String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AutoRestartTask {
    pub id: String,
    pub time: String,
    pub enabled: bool,
    pub description: Option<String>,
}

impl Default for AppConfig {
    fn default() -> Self {
        let mut settings = HashMap::new();
        settings.insert("auto_backup".to_string(), "false".to_string());
        
        Self {
            install_path: "".to_string(),
            steamcmd_path: "".to_string(),
            scum_server_exe_path: "".to_string(),
            scum_server_installed: false,
            frp_dir: "".to_string(),
            frp_installed: false,
            frp_running: false,
            frp_config: HashMap::new(),
            scum_server_running: false,
            auto_restart_tasks: Vec::new(),
            settings,
        }
    }
}

impl AppConfig {
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self::default()
    }

    pub fn load() -> Result<Self, String> {
        let config_path = Self::get_config_path();
        
        if !Path::new(&config_path).exists() {
            // 如果配置文件不存在，创建默认配置
            let config = Self::default();
            config.save()?;
            return Ok(config);
        }
        
        let content = fs::read_to_string(&config_path)
            .map_err(|e| format!("读取配置文件失败: {}", e))?;
        
        serde_json::from_str(&content)
            .map_err(|e| format!("解析配置文件失败: {}", e))
    }

    pub fn save(&self) -> Result<(), String> {
        let config_path = Self::get_config_path();
        
        // 确保配置目录存在
        if let Some(parent) = Path::new(&config_path).parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)
                    .map_err(|e| format!("创建配置目录失败: {}", e))?;
            }
        }
        
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| format!("序列化配置失败: {}", e))?;
        
        fs::write(&config_path, content)
            .map_err(|e| format!("保存配置文件失败: {}", e))
    }

    pub fn update_install_path(&mut self, path: String, installed: bool) -> Result<(), String> {
        self.install_path = path.clone();
        self.steamcmd_path = format!("{}\\steamcmd.exe", path);
        self.scum_server_exe_path = format!("{}\\steamapps\\common\\SCUM Server\\SCUM\\Binaries\\Win64\\SCUMServer.exe", path);
        self.scum_server_installed = installed;
        self.save()
    }

    pub fn update_frp_path(&mut self, frp_dir: String, installed: bool) -> Result<(), String> {
        self.frp_dir = frp_dir;
        self.frp_installed = installed;
        self.save()
    }

    pub fn set_frp_running(&mut self, running: bool) -> Result<(), String> {
        self.frp_running = running;
        self.save()
    }

    pub fn set_scum_server_running(&mut self, running: bool) -> Result<(), String> {
        self.scum_server_running = running;
        self.save()
    }

    pub fn add_auto_restart_task(&mut self, task: AutoRestartTask) -> Result<(), String> {
        println!("添加定时重启任务: {:?}", task); // 调试日志
        self.auto_restart_tasks.push(task);
        println!("当前任务数量: {}", self.auto_restart_tasks.len()); // 调试日志
        self.save()
    }

    pub fn remove_auto_restart_task(&mut self, task_id: &str) -> Result<(), String> {
        self.auto_restart_tasks.retain(|task| task.id != task_id);
        self.save()
    }

    pub fn update_auto_restart_task(&mut self, task_id: &str, enabled: bool) -> Result<(), String> {
        if let Some(task) = self.auto_restart_tasks.iter_mut().find(|t| t.id == task_id) {
            task.enabled = enabled;
            self.save()?;
        }
        Ok(())
    }

    pub fn get_auto_restart_tasks(&self) -> &Vec<AutoRestartTask> {
        &self.auto_restart_tasks
    }

    pub fn get_frp_exe_path(&self) -> String {
        if self.frp_dir.is_empty() {
            return String::new();
        }
        format!("{}\\frpc.exe", self.frp_dir)
    }

    pub fn is_frp_installed(&self) -> bool {
        !self.frp_dir.is_empty() && std::path::Path::new(&self.get_frp_exe_path()).exists()
    }

    pub fn get_frp_config(&self, key: &str) -> Option<&String> {
        self.frp_config.get(key)
    }

    pub fn set_frp_config(&mut self, key: String, value: String) -> Result<(), String> {
        self.frp_config.insert(key, value);
        self.save()
    }

    pub fn get_frp_config_all(&self) -> &HashMap<String, String> {
        &self.frp_config
    }

    pub fn set_frp_config_all(&mut self, config: HashMap<String, String>) -> Result<(), String> {
        self.frp_config = config;
        self.save()
    }

    pub fn get_setting(&self, key: &str) -> Option<&String> {
        self.settings.get(key)
    }

    pub fn set_setting(&mut self, key: String, value: String) -> Result<(), String> {
        self.settings.insert(key, value);
        self.save()
    }

    fn get_config_path() -> String {
        // 在用户文档目录下创建配置文件夹
        let config_dir = dirs::document_dir()
            .unwrap_or_else(|| std::path::PathBuf::from("."))
            .join("Ac-God-Panel");
        
        config_dir.join("ac-god-panel-config.json").to_string_lossy().to_string()
    }

    #[allow(dead_code)]
    pub fn get_install_path(&self) -> &str {
        &self.install_path
    }

    #[allow(dead_code)]
    pub fn get_steamcmd_path(&self) -> &str {
        &self.steamcmd_path
    }

    #[allow(dead_code)]
    pub fn get_scum_server_exe_path(&self) -> &str {
        &self.scum_server_exe_path
    }

    #[allow(dead_code)]
    pub fn get_scum_server_install_status(&self) -> bool {
        self.scum_server_installed
    }

    #[allow(dead_code)]
    pub fn is_scum_server_installed(&self) -> bool {
        !self.install_path.is_empty() && Path::new(&self.steamcmd_path).exists()
    }
} 